package com.java1234.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.java1234.entity.WorkReport;
import com.java1234.entity.PageBean;
import com.java1234.entity.R;
import com.java1234.service.WorkReportService;
import com.java1234.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 工作汇报表 前端控制器
 * </p>
 *
 * @author zhai
 * @since 2025-05-10
 */
@RestController
@RequestMapping("/sys/workReport")
public class WorkReportController {
    @Autowired
    private WorkReportService service;

    @PostMapping("/save")
    public R save(@RequestBody WorkReport entity){
        if(entity.getId()==null || entity.getId()==-1){
            // 检查今天是否已经提交过
            if(hasSubmittedToday(entity.getUserId())) {
                return R.error("每天只能提交一次工作汇报，请修改已有汇报");
            }
            entity.setReportTime(new Date());
            entity.setMonth(new Date().getMonth()+1);// 月份从0开始，所以要加1
            service.save(entity);
        }else{
            service.updateById(entity);
        }
        return R.ok();
    }

    @PostMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        String query = pageBean.getQuery() != null ? pageBean.getQuery().trim() : "";
        String query2 = pageBean.getQuery2() != null ? pageBean.getQuery2().trim() : "";
        Page<WorkReport> pageResult = service.page(
                new Page<>(pageBean.getPageNum(), pageBean.getPageSize()),
                new QueryWrapper<WorkReport>()
                        .like(StringUtil.isNotEmpty(query), "content", query)
                        .eq(StringUtil.isNotEmpty(query2), "username", query2)
                        .orderByDesc("id") // 改为查询bumen字段而不是username
        );
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("list",pageResult.getRecords());
        resultMap.put("total",pageResult.getTotal());
        return R.ok(resultMap);
    }

    @PostMapping("/delete")
    @Transactional
    public R delete(@RequestBody Long[] ids){
        service.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    @GetMapping("/info/{id}") // 添加这个接口匹配前端请求
    public R info(@PathVariable(value = "id") Long id){
        WorkReport entity = service.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("bumen",entity); // 改为"bumen"匹配前端期望
        return R.ok(map);
    }


    // 检查用户今天是否已经提交过
    private boolean hasSubmittedToday(Integer userId) {
        // 获取今天的开始和结束时间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date startOfDay = calendar.getTime();

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date endOfDay = calendar.getTime();

        // 查询该用户今天是否已有汇报
        QueryWrapper<WorkReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .ge("report_time", startOfDay)
                .le("report_time", endOfDay);

        return service.count(queryWrapper) > 0;
    }

}
